// packageFT/guide/my/my.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  options: {
    styleIsolation: 'shared',
  },
  data: {
    scrollTop: 0,
    uploadNumber: 10,
    readonly: false,
    uploadUrl: 'upload.uploadPic',
    formData:{
      store_id:'',
      cityString:'',
      province_id:'',
      city_id:'',
      title:'',
      thumb:'',
      thumb_url:[],
      content_text:'',
      dayvalue:1,
      param:[],
      options:[]
    },
    imgData:[],
    strokeData:[
      {'dayNumber':'D1','AttractionsArr':[]}
    ],
    dayIndex:'',
    jingdianIndex:'',
    AttractionsStatus: false,
    attractionsList:[
      
    ],
    nameNumber:5,
    responsibleAreaOptions: [],
    cascaderStatus: false,
    responsibleAreaShow: false,
    showCalendar: false,
    priceArr:[],
    // store_id:''
  },
  unique(arr){
    let res = []
    for (let i = 0; i < arr.length; i++) {
    if (res.indexOf(arr[i]) === -1) {
    res.push(arr[i])
    }
    }
    return res
  },
  onFocus(e){
    let jianpanheight = e.detail.height
    this.setData({
      scrollTop:jianpanheight
    })
  },
  getjingdianlist(provinceID,cityID){
    const _this = this
    let urlStr = app.getNetAddresss("scenicSpots.list.index");
    app._getNetWork({
      url: urlStr,
      data: {'province_id':provinceID,'city_id':cityID},
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          console.log(resData,'------------fgghhj')
          _this.setData({
            'attractionsList': resData.data
          })
        } else {
          app.tips(resData.msg)
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },
  deletePictFn(e){
    let deleteItemIndex = e.currentTarget.dataset.index
    this.data.formData.thumb_url.splice(deleteItemIndex,1)
    this.setData({
      'formData.thumb_url':this.data.formData.thumb_url
    })
  },
  showCascader(){
    if(this.data.readonly){
      return false
    }
    this.setData({
      cascaderStatus: true
    })
  },
  showCascaderFn(){
    this.setData({
      showCalendar: true
    })
  },
  onCloseCalendar(){
    this.setData({
      showCalendar: false
    })
  },
  onConfirmCalendar(event){
    this.data.priceArr = []
    const [start, end] = event.detail;
    let startTime = new Date(start).getTime()
    let endTime = new Date(end).getTime()
    let dayNumber = (endTime-startTime)/86400000
    console.log(dayNumber)
    if(dayNumber>1){
      let startDay = this.timestamp(startTime)
      let endDay = this.timestamp(endTime)
      this.data.priceArr.push({'date':startDay,price:'',stock:999})
      for(let i=0;i<(dayNumber-1);i++){
        let priceItemJson = {
          'date':'',
          'price':'',
          'stock':999
        }
        let nextDay = this.timestamp(startTime+((i+1)*86400000))
        priceItemJson.date = nextDay
        this.data.priceArr.push(priceItemJson)
      }
      this.data.priceArr.push({'date':endDay,price:'','stock':999})
    } else {
      let startDay = this.timestamp(startTime)
      let endDay = this.timestamp(endTime)
      this.data.priceArr.push({'date':startDay,price:''})
      this.data.priceArr.push({'date':endDay,price:''})
    }
    console.log(this.data.priceArr)
    this.setData({
      priceArr:this.data.priceArr,
      showCalendar: false
    })
  },
  timestamp(timestamp){
    const date = new Date(timestamp);
    const year = date.getFullYear()
    const month = ('0' + (date.getMonth() + 1)).slice(-2);
    const day = ('0' + date.getDate()).slice(-2);
    const formattedDate = year + '年' + month + '月' + day + '日'
    return formattedDate
  },
  onChangePrice(e){
    console.log(e)
    this.data.priceArr[e.currentTarget.dataset.index].price = e.detail
    this.setData({
      priceArr:this.data.priceArr
    })
  },
  deletePrice(e){
    this.data.priceArr.splice(e.currentTarget.dataset.index,1)
    this.setData({
      priceArr:this.data.priceArr
    })
  },
  saveFn(){
    if(!this.data.formData.cityString){
      wx.showToast({
        icon:'none',
        title: '请选择城市',
      })
      return false
    }
    if(!this.data.formData.title){
      wx.showToast({
        icon:'none',
        title: '请填写线路名称',
      })
      return false
    }
    if(this.data.formData.thumb_url.length == 0){
      wx.showToast({
        icon:'none',
        title: '请上传商品路线图',
      })
      return false
    }
    if(!this.data.formData.content_text){
      wx.showToast({
        icon:'none',
        title: '请填写旅游路线详情',
      })
      return false
    }
    // let xingchengonoff = false
    // this.data.strokeData.forEach((item)=>{
    //   if(item.AttractionsArr.length == 0){
    //     xingchengonoff = true
    //   }
    // })
    // if(xingchengonoff){
    //   wx.showToast({
    //     icon:'none',
    //     title: '请完善行程数据选择景点',
    //   })
    //   return false
    // }
    if(this.data.priceArr.length == 0){
      wx.showToast({
        icon:'none',
        title: '请选择出发时间',
      })
      return false
    }
    let priceonoff = false;
    // let renshuonoff = false
    this.data.priceArr.forEach((item)=>{
      if(item.price == ''){
        priceonoff = true
      }
      // if(item.stock == ''){
      //   renshuonoff = true
      // }
    })
    if(priceonoff){
      wx.showToast({
        icon:'none',
        title: '请填写价格',
      })
      return false
    }
    // if(renshuonoff){
    //   wx.showToast({
    //     icon:'none',
    //     title: '请填写人数'
    //   })
    //   return false
    // }
    this.setData({
      'formData.thumb':this.data.formData.thumb_url[0]
    })
    let newparam = []
    this.data.strokeData.forEach((item)=>{
      let newparamitem = {
        'id':'',
        'title':'',
        'value':''
      }
      newparamitem.title = item.dayNumber
      let addressArr = []
      item.AttractionsArr.forEach((ite)=>{
        addressArr.push(ite.name)
      })
      newparamitem.value = addressArr.join('/');
      newparam.push(newparamitem)
    })
    this.setData({
      'formData.param':newparam
    })
    this.setData({
      'formData.options':this.data.priceArr
    })
    console.log(this.data.formData)
    wx.showLoading({
      title: '加载中...',
    })
    let newFormData = JSON.parse(JSON.stringify(this.data.formData))
    newFormData.options.forEach((item)=>{
      let newDateyear = item.date.replace('年','-')
      let newDateyue = newDateyear.replace('月','-')
      let newDate = newDateyue.replace('日','')
      item.date = newDate
    })
    const _this = this
    let urlStr = ''
    if(this.data.formData.store_id){
      urlStr = app.getNetAddresss("plugin.travel-agency.frontend.store.goods.add-goods");
    } else {
      urlStr = app.getNetAddresss("plugin.talent.frontend.goods.add-goods");
    }
    app._postNetWork({
      url: urlStr,
      data: newFormData,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          console.log(resData,'------------fgghhj')
          wx.showToast({
            title: resData.msg,
            duration: 1500
          })
          wx.navigateBack({
            delta:-1
          })
        } else {
          app.tips(resData.msg)
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },
  responsibleAreaFinish(e){
    console.log(e,'-----------------------fgh')
    const {selectedOptions, tabIndex, value } = e.detail
    let cityname = ''
    let provinceID = ''
    let cityID = ''
    selectedOptions.forEach((item,index)=>{
      if(index !== 0){
        cityID = item.value
        cityname +='-'
        this.getjingdianlist(provinceID,cityID)
      } else {
        provinceID = item.value
      }
      cityname += item.text
    })
    this.setData({
      'formData.province_id':provinceID,
      'formData.city_id':cityID,
      'formData.cityString' : cityname,
      cascaderStatus: false
    })
  },
  popupToggle(){
    this.setData({
      cascaderStatus: false
    })
  },
  changeContent(e){
    this.setData({
      'formData.content_text':e.detail
    })
  },
  changeName(e){
    console.log(e)
    this.setData({
      'formData.title':e.detail
    })
  },
  /**
   * 上传图片
   */
  upPicture() {
    let that = this;
    let number = that.data.uploadNumber - that.data.formData.thumb_url.length;
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    wx.chooseImage({
      count: number,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        console.log(res);
        for (let j = 0; j < tempFilePaths.length; j++) {
          wx.compressImage({
            src: tempFilePaths[j], // 图片路径
            quality: 60, // 压缩质量
            success(e) {
              console.log(e);
              let photourl = e.tempFilePath;
              wx.uploadFile({
                url: urlStr,
                filePath: photourl,
                name: 'file',
                success(resdata) {
                  let res = JSON.parse(resdata.data);
                  if (res.result == 1) {
                    let imageUrl1 = res.data.img_url;
                    let imgData = that.data.imgData;
                    imgData.push(imageUrl1);
                    that.setData({
                      'formData.thumb_url': imgData
                    });
                  } else {
                    wx.showToast({
                      icon: 'none',
                      title: res.msg,
                      duration: 1500
                    });
                  }
                }
              });
            },
            fail(e) {},
            complete(e) {}
          });
        }
      }
    });
  },
  /**
   * 选择出行天数生成行程数据方法
   */
  dayChange(e){
    console.log(e.detail)
    this.data.attractionsList.forEach((item,index)=>{
      item['disabled'] = false
    })
    let xingchengArr = []
    for(let i=0;i<e.detail;i++){
      let xingchengItem = {
        'dayNumber':'D'+(i+1),
        'AttractionsArr':[]
      }
      xingchengArr.push(xingchengItem)
    }
    this.setData({
      'formData.dayvalue':e.detail,
      strokeData:xingchengArr,
      attractionsList: this.data.attractionsList
    })
  },
  /**
   * 添加景点按钮
   */
  addAttractions(e){
    if(this.data.strokeData[e.currentTarget.dataset.dayindex].AttractionsArr.length == 10){
      wx.showToast({
        title: '一天最多选择十个景点'
      })
      return false
    }
    this.setData({
      AttractionsStatus:true,
      dayIndex: e.currentTarget.dataset.dayindex
    })
  },
  deleteAttractions(e){
    let jingdianindex = e.currentTarget.dataset.attractionsindex;
    let dayindex = e.currentTarget.dataset.dayindex
    let name = this.data.strokeData[dayindex].AttractionsArr[jingdianindex].name
    this.data.attractionsList.forEach((item,index)=>{
      if(item.name == name){
        item.disabled = false
      }
    })
    this.data.strokeData[dayindex].AttractionsArr.splice(jingdianindex,1)
    this.setData({
      strokeData: this.data.strokeData,
      attractionsList: this.data.attractionsList
    });
  },
  /**
   * 添加景点方法
   */
  selectAttractionsFn(e){
    // let number = 0
    // this.data.attractionsList.forEach((item,index)=>{
    //   if(item.selectStatus){
    //     number +=1
    //   }
    // })
    // if(number == 10){
    //   wx.showToast({
    //     title: '一天最多选择是个景点'
    //   })
    //   return false
    // }
    this.data.attractionsList.forEach((item,index)=>{
      if(index === e.currentTarget.dataset.index){
        if(!item.disabled){
          if(item.selectStatus){
            item.selectStatus = false
          } else {
            item.selectStatus = true
          }
        }
      }
    })
    this.setData({
      attractionsList: this.data.attractionsList
    });
  },
  /**
   * 确认选择景点
   */
  confirmSelectFn(){
    const _this = this
    this.data.attractionsList.forEach((item)=>{
      if(item.selectStatus){
        item.selectStatus = false
        item['disabled'] = true
        _this.data.strokeData[_this.data.dayIndex].AttractionsArr.push(item)
      }
    })
    this.setData({
      attractionsList:this.data.attractionsList,
      strokeData:this.data.strokeData,
      AttractionsStatus:false
    })
  },
  onCloseTopicPopup(){
    this.data.attractionsList.forEach((item,index)=>{
      item['selectStatus'] = false
    })
    this.setData({
      attractionsList:this.data.attractionsList,
      AttractionsStatus:false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.type=='lookup'){
      this.setData({
        readonly:true
      })
      this.getgoodsdetails(options.goodsid)
    } else {
      this.getAddress()
      this.getjingdianlist('','')
    }
    if(options.store_id){
      this.setData({
        'formData.store_id':options.store_id
      })
    }
  },
  getgoodsdetails(id){
    wx.showLoading({
      title: '加载中...',
    })
    const _this = this
    let urlStr = app.getNetAddresss("plugin.talent.frontend.goods.goods-detail");
    app._getNetWork({
      url: urlStr,
      data: {'goods_id':id},
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          let newstrokeData = []
          resData.data.param.forEach((item)=>{
            let itemjson = {
              id:'',
              dayNumber:item.title,
              AttractionsArr:[]
            }
            if(item.value){
              let valueArr = item.value.split('/')
              valueArr.forEach((ite)=>{
                let valueArritem ={'name':ite}
                itemjson.AttractionsArr.push(valueArritem)
              })
              newstrokeData.push(itemjson)
            }
          })
          _this.setData({
            'formData.cityString':resData.data.city_name,
            'formData.title':resData.data.title,
            'formData.thumb_url':resData.data.thumb_url,
            'formData.content_text':resData.data.content,
            'formData.dayvalue':resData.data.param.length,
            strokeData:newstrokeData,
            priceArr:resData.data.options
          })
        } else {
          app.tips(resData.msg)
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },
  /**
   * 获取省市列表(出行城市)
   */
  getAddress: function() {
    wx.showLoading({
      title: '加载中...',
    })
    const _this = this
    let urlStr = app.getNetAddresss("member.member-address.address");
    app._postNetWork({
      url: urlStr,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          const thirdLevelRegion = resData.data.province.map(item => {
            const child = resData.data.city.filter(item1 => item1.parentid == item.id).map(item1 => {
              const child2 = resData.data.district.filter(item2 => item2.parentid == item1.id).map(item2 => {
                return {
                  text: item2.areaname,
                  value: item2.id + ''
                }
              })
              return {
                text: item1.areaname,
                value: item1.id + '',
                children: child2
              }
            })
            return {
              text: item.areaname,
              value: item.id + '',
              children: child
            }
          })
          const secondaryRegion = resData.data.province.map(item => {
            const child = resData.data.city.filter(item1 => item1.parentid == item.id).map(item1 => {
              return {
                text: item1.areaname,
                value: item1.id + ''
              }
            })
            return {
              text: item.areaname,
              value: item.id + '',
              children: child
            }
          })
          _this.setData({ 
            registerAreaOptions: thirdLevelRegion,
            responsibleAreaOptions: secondaryRegion
          })
        } else {
          app.tips(resData.msg)
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})